#!/usr/bin/python
# -*- coding: utf-8 -*-

import re
import sys
import time
import socket
import urllib
import MySQLdb

socket.setdefaulttimeout(5)

def GetInfo(reg, data):
    m = re.search(reg, data)
    if m:
    	return m.group(1)
    return -1

def UpdateInfo(id):
    url = "http://api.youku.com/api_ptvideoinfo/pid/XMTI5Mg==/id/" + id + "/rt/xml"
    data = urllib.urlopen(url).read()
    
    pv = GetInfo(r'<pv>(.*)</pv>', data)
    totalcomment = GetInfo(r'<totalcomment>(.*)</totalcomment>', data)
    fav = GetInfo(r'<fav>(.*)</fav>', data)
    up = GetInfo(r'<up>(.*)</up>', data)
    down = GetInfo(r'<down>(.*)</down>', data)
    reference = GetInfo(r'<reference>(.*)</reference>', data)
    state = GetInfo(r'<state>(.*)</state>', data)
    publicType = GetInfo(r'<publicType>(.*)</publicType>', data)
    
    print fav
    if pv != -1:
        cur.execute("update video_info set pv=" + pv + ", " + \
                "totalcomment=" + totalcomment + ", " + \
                "fav=" + fav + ", " + \
                "up=" + up + ", " + \
                "down=" + down + ", " + \
                "reference=" + reference + ", " + \
                "state=" + state + ", " + \
                "publicType=" + publicType + " where id='" + id + "'")

#得到X天前的日期 
ISOTIMEFORMAT='%Y-%m-%d'
cur_time = time.time()
day = sys.argv[1]
from_time = cur_time - int(day) * 24 * 3600;
from_time_str = time.strftime(ISOTIMEFORMAT, time.localtime(from_time))
to_time = cur_time - (int(day) - 1) * 24 * 3600;
to_time_str = time.strftime(ISOTIMEFORMAT, time.localtime(to_time))

#连接数据库
conn = MySQLdb.Connection("172.16.7.58", "root", "researchsucks", "X", 3306)
conn.set_character_set("utf8");
cur = conn.cursor()

#执行查询
cur.execute("select id from video_info where pubdate>=date('" + from_time_str + \
        "') and pubdate<date('" + to_time_str + "')")

#更新此日视频信息
for data in cur.fetchall():
    try:
        id = data[0]
        print day,id
        UpdateInfo(id)
    except:
        print "error###"

cur.close()
conn.close()
